<?php

declare(strict_types=1);

namespace App\Service\Business;

use App\Service\Access\UserRoleAccess;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 用户角色-业务类
 */
class UserRoleBusiness extends BaseBusiness
{
        #[Inject]
        protected UserRoleAccess $UserRoleAccess;

        /**
         * 分配
         * @return array
         * @throws ContainerExceptionInterface
         * @throws NotFoundExceptionInterface
         */
        public function setting(): array
        {
                $arrData = $this->UserRoleAccess->forPage([
                        'wheres' => ['userId' => $this->request->input('userId')], 'page' => 1, 'limit' => 1000]);
                $arrRoleIds = $this->request->input('roleIds', []);
                $arrInserts = [];
                foreach ($arrRoleIds as $v) {
                        $arrInserts[] = [
                                'userRoleId' => snowflakeId(),
                                'userId' => $this->request->input('userId'),
                                'roleId' => $v
                        ];
                }
                $this->UserRoleAccess->delete(['wheres' => ['userId' => $this->request->input('userId')]]);
                $arrInserts && $this->UserRoleAccess->insert($arrInserts);
                $this->createOperateLog($arrData, $arrInserts);
                return businessSuccess();
        }

        /**
         * 分页
         * @param array $inject
         * @return array
         */
        public function paginate(array $inject = []): array
        {
                $arrQueryResult = $this->UserRoleAccess->paginate($inject);
                $arrResult = [
                        'page' => $arrQueryResult['current_page'],
                        'limit' => $arrQueryResult['per_page'],
                        'total' => $arrQueryResult['total'],
                        'list' => $arrQueryResult['data'],
                ];
                return businessSuccess($arrResult);
        }
}